{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "db512135",
   "metadata": {},
   "source": [
    "--------\n",
    "* 记录人：庄焕敏\n",
    "* 时间：2021-12-2\n",
    "* week14\n",
    "* 主要参考文档\n",
    "\n",
    ">[python官方文档](https://python.org)（4.7/4.8）\n",
    "\n",
    ">[gitee课堂笔记](https://gitee.com/xzhichao/python)\n",
    "\n",
    ">[许老师的博客](https://cnblogs.com/xuzhichao)\n",
    "--------"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8f672c98",
   "metadata": {},
   "source": [
    "# 1.函数\n",
    "\n",
    "## 1.函数的定义\n",
    "##### （https://docs.python.org/3/tutorial/controlflow.html#defining-functions）\n",
    "> 1.数学：     f(x)=ax+b   \n",
    "> 2.python: def fib(x)：   \n",
    "> 3.编程思维 VS 数学思维    \n",
    ">> 1.函数可以被定义名称，定义的关键字 <font style=\"color:red\">**def**</font>    \n",
    ">> 2.数学思维是写在同一行（定义函数 和 运算公式），面向对象编程中 函数写多行，定义函数为单独一行    \n",
    ">> 3.数字函数一般没有注释，而编程过程中，一般需要对函数进行注释描述（docstring,课本P151）    \n",
    ">> 4.数学中，ax+b是计算公式，而编程中，我们将函数的内容成为**函数体**，函数体要有一定的**缩进**   \n",
    ">> 5.数字函数执行，将参数带入公式， 编程中函数执行，将参数带入函数体      \n",
    "\n",
    "##  2.关于函数的更多定义\n",
    "##### （https://docs.python.org/3/tutorial/controlflow.html#more-on-defining-functions）\n",
    "> 1.函数的参数\n",
    ">> 1.形式参数  \n",
    ">> 2.实际参数   \n",
    ">> 3.默认参数   \n",
    ">> 4.位置参数  \n",
    ">> 5.关键字参数 \n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f50603a7",
   "metadata": {},
   "source": [
    "## 2.函数的定义\n",
    "> 1.定义函数"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0f009e22",
   "metadata": {},
   "source": [
    "def:定义函数的关键字   \n",
    "flb：函数名    \n",
    "(n)：定义函数的参数    \n",
    "\"\"\"  \"\"\"：文档描述 : 与使用者进行 交互的唯一途径    \n",
    "代码块：   \n",
    "     a, b = 0, 1   \n",
    "     while a < n:    \n",
    "        print(a, end=' ')    \n",
    "         a, b = b, a+b    \n",
    "     print()    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "9ceefd45",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 斐波那切数列：0 1 1 2 3 5 8 13 21 34...\n",
    "def fib(x):\n",
    "    \"\"\"列出指定x以内的斐波那契数列\"\"\"\n",
    "    a,b = 0,1\n",
    "    while a<x:\n",
    "        print(a,end=\" \")\n",
    "        a,b = b,a+b\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "d4d0e7ff",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 1 1 2 3 5 8 13 21 34 55 89 "
     ]
    }
   ],
   "source": [
    "fib(100)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "e20cfc96",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 实践：写一个函数，这个函数可以打印“你好，某某同学”"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "18566d9d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 初尝试\n",
    "def fib(x):\n",
    "    print(\"你好\",x,\"同学\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "fd42cf81",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "你好 焕敏 同学\n"
     ]
    }
   ],
   "source": [
    "fib(\"焕敏\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "d30f0bd4",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 老师版本\n",
    "def hello(name):\n",
    "    \"\"\"显示问候语\"\"\"\n",
    "    print(\"你好，%s同学\"%(name))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "246eb942",
   "metadata": {},
   "source": [
    ">2.调用函数/使用函数  \n",
    ">>1.函数名(参数)   \n",
    ">>2.参数可以不存在  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "82bbe70a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "你好，Lihua同学\n"
     ]
    }
   ],
   "source": [
    "hello(\"Lihua\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "f90f8b51",
   "metadata": {},
   "outputs": [],
   "source": [
    "def hello():\n",
    "    \"\"\"显示问候语\"\"\"\n",
    "    print(\"hello,world\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "7d0f8660",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on function hello in module __main__:\n",
      "\n",
      "hello()\n",
      "    显示问候语\n",
      "\n"
     ]
    }
   ],
   "source": [
    "help(hello)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "171022c3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello,world\n"
     ]
    }
   ],
   "source": [
    "hello()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "21a506c4",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 回顾与思考\n",
    "import time"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "7e561a0b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# sleeep() 需要给定一个时间（int）参数\n",
    "time.sleep(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "ea0f218e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "time.struct_time(tm_year=2021, tm_mon=12, tm_mday=27, tm_hour=12, tm_min=10, tm_sec=23, tm_wday=0, tm_yday=361, tm_isdst=0)"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# localtime() 不需要给定参数\n",
    "time.localtime()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "a7867366",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on built-in function localtime in module time:\n",
      "\n",
      "localtime(...)\n",
      "    localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n",
      "                              tm_sec,tm_wday,tm_yday,tm_isdst)\n",
      "    \n",
      "    Convert seconds since the Epoch to a time tuple expressing local time.\n",
      "    When 'seconds' is not passed in, convert the current time instead.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "help(time.localtime)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3aff5e87",
   "metadata": {},
   "source": [
    "> 3.函数的优势          \n",
    ">> 1.可以重复使用相同的功能，避免重复造轮子         \n",
    ">> 2.使用者可以不了解函数本身，只需要清楚如何使用即可            \n",
    ">> 3.使用/调用方便，只需要清楚传递的 函数名及参数"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "43278c66",
   "metadata": {},
   "source": [
    "# 3.函数的参数\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "48b1ca82",
   "metadata": {},
   "source": [
    ">1.形式参数（形参）形式参数，不是实际存在的，是虚拟变量。在定义函数和函数体的时候使用形参，目的是在函数调用时接收实参        \n",
    ">>1.在**定义**函数的时候定义的参数           \n",
    ">>2.形式参数不占用内存\n",
    "\n",
    ">2.实际参数（实参）实际参数，调用函数时传递给函数的参数，可以是常量、变量，表达式，函数，传给形参          \n",
    ">>1.在**调用**函数的时候传递的参数   \n",
    ">>2.调用参数时，形式参数分配空间，传递实际参数，执行函数内容"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "c990ec2f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 课本函数实践案例\n",
    "def search4vowels(word):\n",
    "    \"\"\"显示文本中出现的元音字母有哪些\"\"\"\n",
    "    vowels =set(\"aeiou\")\n",
    "    word = set(word)\n",
    "    print(vowels & word)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "409e0e97",
   "metadata": {},
   "source": [
    ">1.形式参数： word   \n",
    ">2.实际参数：\"fbheduigpewjiewmcfkdlaepw\"   "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "17513e9b",
   "metadata": {},
   "outputs": [],
   "source": [
    "#  课本函数实践案例\n",
    "def search4vowels(word):\n",
    "    \"\"\"\n",
    "    显示文本中出现的元音字母有哪些\n",
    "    \n",
    "    word是文本信息，请输入正确的文本给word\n",
    "    \"\"\"\n",
    "    vowels = set(\"aeiou\")\n",
    "    word = set(word)\n",
    "    print(vowels & word)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "cad597db",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on function search4vowels in module __main__:\n",
      "\n",
      "search4vowels(word)\n",
      "    显示文本中出现的元音字母有哪些\n",
      "    \n",
      "    word是文本信息，请输入正确的文本给word\n",
      "\n"
     ]
    }
   ],
   "source": [
    "help(search4vowels)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "35597ff7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'a', 'i', 'u', 'e'}\n"
     ]
    }
   ],
   "source": [
    "search4vowels(\"fbheduigpewjiewmcfkdlaepw\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "914fd8db",
   "metadata": {},
   "source": [
    " * 在多个参数的情境下\n",
    " >1.位置参数(positional argument)  \n",
    " >> 1. 在形式参数的定义中，有一定的先后顺序\n",
    " >> 2. 在调用函数时，要考虑形参的先后顺序\n",
    " >> 3. 调用函数时，不仅要考虑参数位置，还需要考虑形式参数的个数\n",
    " \n",
    " > 2. 关键字参数\n",
    " >> 1. 在调用函数时，关键字参数可以不考虑形式参数的位置\n",
    " \n",
    " > 3. 默认参数\n",
    " >> 1. 调用函数时，可以省略传递的参数信息\n",
    " >> 2. 调用函数时，如果给默认参数赋值，会替换默认参数的结果  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "41e00952",
   "metadata": {},
   "outputs": [],
   "source": [
    "def describe_pet(pet_name,animal_type):\n",
    "    \"\"\"显示宠物信息\"\"\"\n",
    "    print(\"\\nI have a \" + animal_type + \".\")\n",
    "    print(\"My \" + animal_type + \"'s name is \"+pet_name.title() + \".\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "9b7dc41d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "I have a dog.\n",
      "My dog's name is 壮壮.\n"
     ]
    }
   ],
   "source": [
    "describe_pet(\"壮壮\",\"dog\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "f8046edd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "I have a 壮壮.\n",
      "My 壮壮's name is Dog.\n"
     ]
    }
   ],
   "source": [
    "describe_pet(\"dog\",\"壮壮\")  # 顺序反不了"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "ec0d8d57",
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "describe_pet() missing 1 required positional argument: 'animal_type'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32mC:\\Users\\ZHUANG~1\\AppData\\Local\\Temp/ipykernel_20180/1346824171.py\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mdescribe_pet\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"壮壮\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m: describe_pet() missing 1 required positional argument: 'animal_type'"
     ]
    }
   ],
   "source": [
    "describe_pet(\"壮壮\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "9a1c591a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "I have a cat.\n",
      "My cat's name is 小美.\n"
     ]
    }
   ],
   "source": [
    "describe_pet(animal_type=\"cat\",pet_name=\"小美\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "63bffe23",
   "metadata": {},
   "outputs": [],
   "source": [
    "## 默认参数\n",
    "def describe_pet(pet_name,animal_type=\"dog\"):\n",
    "    \"\"\"显示宠物信息\"\"\"\n",
    "    print(\"\\nI have a \" + animal_type + \".\")\n",
    "    print(\"My \" + animal_type + \"'s name is \"+pet_name.title() + \".\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "bc738d74",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "I have a cat.\n",
      "My cat's name is 小美.\n"
     ]
    }
   ],
   "source": [
    "describe_pet(\"小美\",\"cat\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5f09e186",
   "metadata": {},
   "source": [
    "* 参数注意事项实践\n",
    "> 1. 位置参数和关键字参数同时使用（调用函数）\n",
    ">> 1. positional argument follows keyword argument（关键字参数均应该放在位置参数之后）\n",
    ">> 2. 只要满足1的条件，剩余的关键字参数（多个）不考虑先后顺序\n",
    "\n",
    " > 2. 非默认参数和默认参数同时使用（定义函数）\n",
    " >> 1. non-default argument follows default argument（默认参数均应该放在非默认参数之 后）\n",
    " >> 2. 只要满足1的条件，剩余的默认参数（多个）不考虑先后顺序"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "08457a7e",
   "metadata": {},
   "outputs": [],
   "source": [
    "def test(x,y,z):\n",
    "    \"\"\"打印x,y,z的结果\"\"\"\n",
    "    print(x)\n",
    "    print(y)\n",
    "    print(z)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "713a9a33",
   "metadata": {},
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "positional argument follows keyword argument (Temp/ipykernel_20180/3987684605.py, line 2)",
     "output_type": "error",
     "traceback": [
      "\u001b[1;36m  File \u001b[1;32m\"C:\\Users\\ZHUANG~1\\AppData\\Local\\Temp/ipykernel_20180/3987684605.py\"\u001b[1;36m, line \u001b[1;32m2\u001b[0m\n\u001b[1;33m    test(5,y=3,2)\u001b[0m\n\u001b[1;37m                ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m positional argument follows keyword argument\n"
     ]
    }
   ],
   "source": [
    "# 实践1：\n",
    "test(5,y=3,2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "507ecdfd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5\n",
      "3\n",
      "2\n"
     ]
    }
   ],
   "source": [
    "# 实践2：\n",
    "test(5,3,z = 2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "448a7921",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5\n",
      "2\n",
      "3\n"
     ]
    }
   ],
   "source": [
    "# 实践3：\n",
    "test(5,z=3,y=2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "35d5fef1",
   "metadata": {},
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "non-default argument follows default argument (Temp/ipykernel_20180/1178452859.py, line 2)",
     "output_type": "error",
     "traceback": [
      "\u001b[1;36m  File \u001b[1;32m\"C:\\Users\\ZHUANG~1\\AppData\\Local\\Temp/ipykernel_20180/1178452859.py\"\u001b[1;36m, line \u001b[1;32m2\u001b[0m\n\u001b[1;33m    def test(x,y=1,z):\u001b[0m\n\u001b[1;37m                   ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m non-default argument follows default argument\n"
     ]
    }
   ],
   "source": [
    "# 测试2：\n",
    "def test(x,y=1,z):\n",
    "    \"\"\"打印x,y,z的结果\"\"\"\n",
    "    print(x)\n",
    "    print(y)\n",
    "    print(z)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "f5b92d80",
   "metadata": {},
   "outputs": [],
   "source": [
    "def test(x,z,y=1):\n",
    "    \"\"\"打印x,y,z的结果\"\"\"\n",
    "    print(x)\n",
    "    print(y)\n",
    "    print(z)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1fa3cda2",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.0b3"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
